<?php

namespace App\Modules\Apicrzs\Http\Controllers\Auth;

use App\Modules\Apicrzs\Http\Controllers\BaseApicrzsController;
use App\Modules\Apicrzs\Services\Public\LoginWxService;
use App\Modules\Apicrzs\Services\WeChat\RoutineServices;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class LoginControllers extends BaseApicrzsController
{

    public function __construct(LoginWxService $authService)
//    public function __construct(RoutineServices $authService)
    {
        $this->service = $authService;
    }
    /**
     * 登录流程
     */

    public function silenceAuth(Request $request): JsonResponse
    {
        $res = $this->service->silenceAuth($request->all());
        return $this->sendApiSuccess($res, $this->service->getError());
    }

    public function authType(Request $request)
    {
        $res = $this->service->authType($request->all());
        return $this->sendApiSuccess($res, $this->service->getError());
    }
    /**
     * 授权获取小程序用户手机号 直接绑定
     * @param string $code
     * @param string $iv
     * @param string $encryptedData
     * @param string $spread_code
     * @param string $spread_spid
     * @param string $key
     * @return mixed
     */
    public function authBindingPhone(Request $request)
    {
        $data = $this->service->authBindingPhone($request->all());
        if ($data){
            return $this->sendApiSuccess($data);
        }else{
            return $this->sendApiError($this->service->getError());
        }
    }

    /**
 * 小程序手机号登录
 * @param string $key
 * @param string $phone
 * @param string $captcha
 * @param string $spread_code
 * @param string $spread_spid
 * @param string $code
 */
    public function phoneLogin($key = '', $phone = '', $captcha = '', $spread_code = '', $spread_spid = '', $code = '')
    {
        //验证验证码
        $verifyCode = CacheService::get('code_' . $phone);
        if (!$verifyCode)
            return app('json')->fail(410009);
        $verifyCode = substr($verifyCode, 0, 6);
        if ($verifyCode != $captcha) {
            CacheService::delete('code_' . $phone);
            return app('json')->fail(410010);
        }
        CacheService::delete('code_' . $phone);
        $data = $this->services->phoneLogin($key, $phone, $spread_code, $spread_spid, $code);
        return app('json')->success($data);
    }
    /**
     * 小程序绑定手机号
     * @param string $code
     * @param string $iv
     * @param string $encryptedData
     */
    public function bindingPhone($code = '', $iv = '', $encryptedData = '')
    {
        if (!$code || !$iv || !$encryptedData) return app('json')->fail(100100);
        $this->services->bindingPhone($code, $iv, $encryptedData);
        return app('json')->success(410016);
    }
}
